package tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author kaho
 * @since 2021/3/1
 */
public class _199_二叉树的右视图 {

    /**
     * 给定一棵二叉树，想象自己站在它的右侧，按照从顶部到底部的顺序，返回从右侧所能看到的节点值。
     * @param root
     * @return
     */
    public List<Integer> rightSideView2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs1(root, 0, result);
        return result;
    }

    private void dfs1(TreeNode root, int i, List<Integer> result) {
        if (root == null) {
            return;
        }
        if (i == result.size()) {
            result.add(root.val);
        }
        i++;
        dfs1(root.right, i, result);
        dfs1(root.left, i, result);
    }


    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, 0, result);
        return result;
    }

    private void dfs(TreeNode root, int i, List<Integer> result) {
        if (root == null) {
            return;
        }
        if (i == result.size()) {
            result.add(root.val);
        }
        i++;
        dfs(root.right, i, result);
        dfs(root.left, i, result);

    }

    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            TreeNode treeNode = queue.peekLast();
            result.add(treeNode.val);
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left!=null) {
                    queue.offer(poll.left);
                }

                if (poll.right!=null) {
                    queue.offer(poll.right);
                }
            }
        }
        return result;
    }
}
